package com.cjd.common.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.cjd.common.R
import com.cjd.common.activity.BaseActivity

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/7/3
 * description
 */
class LoadingFragment : BaseDialogFragment() {

    override fun getLayoutResId() = R.layout.base_dialog_loading

    override fun initData(view: View) {
        init(view)
    }

    companion object {
        @JvmStatic
        fun newInstance(text: String, isCancelable: Boolean): LoadingFragment {
            val fragment = LoadingFragment()
            val bundle = Bundle()
            bundle.putString("alert", text)
            fragment.arguments = bundle
            fragment.isCancelable = isCancelable
            return fragment
        }
    }

    private fun init(view: View) {
        val text: TextView = view.findViewById(R.id.tv_base_loading)
        if (arguments != null && !TextUtils.isEmpty(arguments!!.getString("alert"))) {
            text.visibility = View.VISIBLE
            text.text = arguments!!.getString("alert")
        } else
            text.visibility = View.GONE
    }
}


fun BaseActivity.showWaitingDialog(text: String, isCancelable: Boolean) {
    var dialog: LoadingFragment? =
        supportFragmentManager.findFragmentByTag("base_waiting") as LoadingFragment?
    if (dialog == null) {
        dialog = LoadingFragment.newInstance(text, isCancelable)
    }
    if (!dialog.isAdded) {
        supportFragmentManager.beginTransaction()
            .add(dialog, "base_waiting")
            .commitAllowingStateLoss()
    }
}

fun BaseActivity.dismissWaitingDialog() {
    val dialog = supportFragmentManager.findFragmentByTag("base_waiting")
    if (dialog != null && dialog.isAdded)
        supportFragmentManager.beginTransaction().remove(dialog).commitAllowingStateLoss()
}


/**
 * Fragment 主题等待框
 * @param text 文本
 * @param isCancelable 是否点击取消  默认 true
 */
fun BaseFragment.showLoadingDialog(
    text: String = "loading...",
    isCancelable: Boolean = true
) {
    if (!isAdded)
        return
    var dialog: LoadingFragment? =
        requireActivity().supportFragmentManager.findFragmentByTag("base_waiting") as LoadingFragment?
    if (dialog == null) {
        dialog = LoadingFragment.newInstance(text, isCancelable)
    }
    if (!dialog.isAdded) {
        requireActivity().supportFragmentManager.beginTransaction()
            .add(dialog, "base_waiting")
            .commitAllowingStateLoss()

    }
}

/**
 * Fragment 隐藏主题等待框
 */
fun BaseFragment.dismissLoadingDialog() {
    if (!isAdded)
        return
    val dialog = requireActivity().supportFragmentManager.findFragmentByTag("base_waiting") as LoadingFragment?
    if (dialog != null && dialog.isAdded)
        requireActivity().supportFragmentManager.beginTransaction().remove(dialog).commitAllowingStateLoss()
}